package com.hdculture.simple.expensemanager.premium;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import com.hdculture.simple.expensemanager.premium.R;

import android.app.Activity;
import android.app.Dialog;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.util.Log;
import android.view.*;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

public class MonthIncomeActivity extends Activity {
    /** Called when the activity is first created. */
	TextView monthText;
	ListView incomeList;
	CoreDBAdapter dbAdapter;
	Button backButton, actionsButton;
	EditText rowIDText;
	String currencySign="$";
	String tag = "MonthIncomeActivity";
	int month=1,year=2011;
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
    	dbAdapter.close();
    	Log.i(tag,"DB Connection Closed");
		super.onPause();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		dbAdapter.open();
		Log.i(tag,"DB Connection Resumed");
		super.onResume();
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.monthincome);
        Intent i = getIntent();
        Bundle b = i.getExtras();
        month=b.getInt("MONTH");
        year=b.getInt("YEAR");
        monthText=(TextView)findViewById(R.id.monthText);
        setMonthText(month);
        //monthText.setText(monthText.getText().toString()+" "+year);
        rowIDText = (EditText)findViewById(R.id.rowIDText);
        actionsButton = (Button)findViewById(R.id.actionsButton);
        monthText.append(" "+year);
        incomeList = (ListView)findViewById(R.id.incomeList);
        dbAdapter= new CoreDBAdapter(this);
        dbAdapter.open();
        Log.i(tag,"DB Connection Open");
        currencySign = dbAdapter.getCurrencySign();
        buildList();
        backButton = (Button)findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
        actionsButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				initializeActionsDialog();
			}
		});
    }
    
    public void initializeActionsDialog(){
    	final Dialog actionsDialog = new Dialog(MonthIncomeActivity.this);
    	actionsDialog.setCancelable(true);
    	actionsDialog.setTitle("actions...");
    	actionsDialog.setContentView(R.layout.actionsdialog);
    	String[] actions = {"Edit","Delete"};
    	ListView actionList = (ListView)actionsDialog.findViewById(R.id.actionsList);
    	actionList.setAdapter(new ArrayAdapter<String>(MonthIncomeActivity.this,android.R.layout.simple_list_item_1,actions));
    	actionList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch(arg2){
				case 0:	//Edit selected
						createEditDialog();
						actionsDialog.dismiss();
						break;
				case 1:	//Delete selected
						createDeleteConfirmDialog();
						actionsDialog.dismiss();
						break;	
				}
			}
		});
    	actionsDialog.show();
    }
    
    public void createEditDialog(){
    	final Dialog editDialog = new Dialog(MonthIncomeActivity.this);
    	editDialog.setContentView(R.layout.addincomedialog);
    	editDialog.setTitle("edit income...");
    	final Button editButton = (Button)editDialog.findViewById(R.id.addButton);
    	final Button cancelButton = (Button)editDialog.findViewById(R.id.cancelButton);
    	final EditText incomeSourceText = (EditText)editDialog.findViewById(R.id.incomeSourceText);
    	final EditText incomeAmountText = (EditText)editDialog.findViewById(R.id.incomeAmountText);
    	editButton.setText(" Update ");
    	String rowIDString = rowIDText.getText().toString();
		final int rowID = Integer.parseInt(rowIDString);
		Cursor c = dbAdapter.getIncomeByRowID(rowID);
		startManagingCursor(c);
		c.moveToNext();
		if(c.isAfterLast()==false){
			incomeSourceText.setText(c.getString(c.getColumnIndexOrThrow("source")));
			incomeAmountText.setText(c.getString(c.getColumnIndexOrThrow("amount")));
		}
    	editButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				String source = incomeSourceText.getText().toString();
				double amount = Double.parseDouble(incomeAmountText.getText().toString());
				dbAdapter.updateIncome(rowID, source, amount);
				Toast.makeText(MonthIncomeActivity.this,"Update Successful!",500);
				buildList();
				editDialog.dismiss();
				rowIDText.setText("");
			}
		});
    	cancelButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				editDialog.dismiss();
				rowIDText.setText("");
			}
		});
    	editDialog.show();
    }
    public void createDeleteConfirmDialog(){
    		final Dialog confirmDialog = new Dialog(MonthIncomeActivity.this);
    		confirmDialog.setContentView(R.layout.confirmdialog);
    		confirmDialog.setTitle("Are you sure?");
    		String rowIDString = rowIDText.getText().toString();
    		final int rowID = Integer.parseInt(rowIDString);
    		Button yesButton = (Button)confirmDialog.findViewById(R.id.yesButton);
    		Button noButton = (Button)confirmDialog.findViewById(R.id.noButton);
    		noButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					confirmDialog.dismiss();
					rowIDText.setText("");
				}
			});
    		yesButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					dbAdapter.deleteIncome(rowID);
					Toast.makeText(MonthIncomeActivity.this, "Delete Successful!", 500);
					confirmDialog.dismiss();
					rowIDText.setText("");
					buildList();
				}
			});
    		confirmDialog.show();
    }
    
    public void buildList(){
    	try{
            Cursor cursor = dbAdapter.fetchIncomeByMonth(month, year);
            startManagingCursor(cursor);
    		cursor.moveToFirst();
    		ArrayList <HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
    		HashMap<String,String> map = new HashMap<String,String>();
    		DecimalFormat df = new DecimalFormat(currencySign+"##,##0.00");
    		System.out.println(cursor.getColumnCount());
    		double amt=0.00;
    		double sum=0.00;
    		String dateString="", monthString="", yearString="";
    		DecimalFormat doubleDigits = new DecimalFormat("00");
    		while(cursor.isAfterLast()==false){
    			map.put("ID",cursor.getString(0));
    			dateString=doubleDigits.format(cursor.getDouble(cursor.getColumnIndexOrThrow("dt")));
    			monthString = doubleDigits.format(cursor.getDouble(cursor.getColumnIndexOrThrow("month")));
    			yearString = doubleDigits.format(cursor.getDouble(cursor.getColumnIndexOrThrow("year")));
    			map.put("DT",dateString+"/"+monthString+"/"+yearString);
    			map.put("SOURCE", cursor.getString(4));
    			amt = cursor.getDouble(5);
    			sum+=amt;
    			map.put("AMOUNT", df.format(amt));
    			mylist.add(map);
    			System.out.println(map.toString());
    			map = new HashMap<String,String>();
    			cursor.moveToNext();
    		}
    		map.put("ID","");
    		map.put("DT","");
    		map.put("SOURCE", "TOTAL:");
    		map.put("AMOUNT",df.format(sum));
    		mylist.add(map);
    		Toast.makeText(getApplicationContext(),"Total Income: "+sum,1000).show();
    		SimpleAdapter mIncomeMap;
    		mIncomeMap = new SimpleAdapter(MonthIncomeActivity.this, mylist, R.layout.allincome_row, new String[]{"ID","DT","SOURCE","AMOUNT"}, new int[]{R.id.ID_CELL,R.id.DT_CELL,R.id.SOURCE_CELL,R.id.AMOUNT_CELL});
    		incomeList.setAdapter(mIncomeMap);
    		cursor.close();
            }catch(Exception ex){
            	ex.printStackTrace();
            }
    }
    public void setMonthText(int month){
    	String monthString = "";
        switch(month){
        case 1:	monthString = "january";break;
        case 2: monthString = "february";break;
        case 3: monthString = "march";break;
        case 4: monthString = "april";break;
        case 5: monthString = "may";break;
        case 6: monthString = "june";break;
        case 7: monthString = "july";break;
        case 8: monthString = "august";break;
        case 9: monthString = "september";break;
        case 10: monthString = "october";break;
        case 11: monthString = "november";break;
        case 12: monthString = "december";break;
        }
        monthText.setText(monthString);
    }
}